package com.yuju.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yuju.common.util.string.StringUtilss;
import com.yuju.model.SessionInfo;
import com.yuju.model.User;
import com.yuju.model.UserModel;

/**
 * 用来处理ServletApi相关事项
 * 如：创建session和cookie
 * @author xue
 * @date 2016-07-05
 *
 */
public class WebUtil {

	/**
	 * 将登录的用户信息放入session中和COOKIE中
	 * @author xue
	 * @date 2016-07-05
	 * @param request Servlet请求对象
	 * @param response Servlet响应客户端对象
	 * @param sessionInfo session信息
	 * @param userModel 用户数据
	 * @param params参数集
	 */
	public static void addUser2SessionAndCookie(HttpServletRequest request, HttpServletResponse response, 
			UserModel userModel) {
		addUser2SessionAndCookie(request, response, userModel, null);
	}

	/**
	 * 将登录的用户信息放入session中和COOKIE中
	 * @author xue
	 * @date 2016-07-05
	 * @param request Servlet请求对象
	 * @param response Servlet响应客户端对象
	 * @param sessionInfo session信息
	 * @param userModel 用户数据
	 * @param params参数集
	 */
	public static void addUser2SessionAndCookie(HttpServletRequest request, HttpServletResponse response, 
			UserModel userModel, String isUseCookie) {
		
		SessionInfo sessionInfo = createSessionInfo(userModel);

		addSession(request, "SessionInfo", sessionInfo);

		if (StringUtilss.isNotNull(isUseCookie) && "Y".equals(isUseCookie))
			addCookie(response, sessionInfo);
	}
	
	/**
	 * 将登录用户信息放入HttpSession中
	 * @author xue
	 * @update 2016-07-20
	 * @param request Servlet请求对象
	 * @param sessionName 用户信息保存在session中的名称
	 * @param sessionInfo 用户信息
	 */
	private static void addSession(HttpServletRequest request, String sessionName, SessionInfo sessionInfo) {
		if (null == sessionName)
			return ;
		if (null == sessionInfo)
			return ;
		if (null == sessionInfo.getUser())
			return ;
		
		sessionInfo.setSessionId(request.getSession().getId());
		request.getSession().setAttribute(sessionName, sessionInfo);
		System.out.println("add sessionInfo:" + sessionInfo.getSessionId() + " " + sessionInfo.getUser().getUserName()); 
	}
	
	/**
	 * 将token写入cookie中
	 * @author xue
	 * @update 2016-07-20
	 * @param request Servlet请求对象
	 * @param sessionInfo 用户信息
	 */
	public static void addCookie4Token(HttpServletResponse response, SessionInfo sessionInfo) {
		if (null == sessionInfo)
			return ;
		if (null == sessionInfo.getUser())
			return ;
		
		String tokenKey = "token";
		Cookie tokenCk = new Cookie(tokenKey, sessionInfo.getToken());
		tokenCk.setPath("/");
		// tokenCk.setMaxAge(60 * 60 * 24 * 365);
		//tokenCk.setMaxAge(60 * 60);
		response.addCookie(tokenCk);
	}
	
	/**
	 * 将登录用户信息写入cookie中
	 * @author xue
	 * @update 2016-07-20
	 * @param request Servlet请求对象
	 * @param sessionName 用户信息保存在session中的名称
	 * @param sessionInfo 用户信息
	 */
	public static void addCookie(HttpServletResponse response, SessionInfo sessionInfo) {
		if (null == sessionInfo)
			return ;
		if (null == sessionInfo.getUser())
			return ;

		User user = sessionInfo.getUser();
		// 用户登录信息写入cookie
		Cookie useridCk = new Cookie("userId", user.getUserId().toString());
		Cookie usercodeCk = new Cookie("userCode", user.getUserCode());
		Cookie usernameCk = null;
		try {
			usernameCk = new Cookie("userName", URLEncoder.encode(user.getUserName(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		useridCk.setMaxAge(60 * 60 * 24 * 365);
		useridCk.setPath("/");
		usercodeCk.setMaxAge(60 * 60 * 24 * 365);
		usercodeCk.setPath("/");
		usernameCk.setMaxAge(60 * 60 * 24 * 365);
		usernameCk.setPath("/");

		response.addCookie(useridCk);
		response.addCookie(usercodeCk);
		response.addCookie(usernameCk);
	}
	
	/**
	 * 获取COOKIES中token
	 * @author xue
	 * @date 2016-07-20 
	 * @return token
	 */
	public static String getTokenFromCookie(HttpServletRequest request, HttpServletResponse response) {
		String token = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equalsIgnoreCase("token")) {
					token = cookie.getValue();
				}
			}
		}
		return token;
	}
	
	/**
	 * 获取COOKIES中用户信息
	 * @author xue
	 * @date 2016-07-20 
	 * @return 用户
	 */
	public static User getUserFromCookie(HttpServletRequest request) {
		User user = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			user = new User();
			for (Cookie cookie : cookies) {
				if (cookie.getName().equalsIgnoreCase("userId"))
					user.setUserId(cookie.getValue());
				else if (cookie.getName().equalsIgnoreCase("userCode"))
					user.setUserCode(cookie.getValue());
				else if (cookie.getName().equalsIgnoreCase("userName"))
					user.setUserName(cookie.getValue());
			}

			if (null != user.getUserId()) {
				return null;
			}
			System.out.println("***从COOKIE得到USER对象信息!");
		}
		return user;
	}

	/**
	 * 判断是否是ajax访问
	 * @author xue
	 * @date 2016-07-22
	 * @param request HttpServletRequest对象
	 * @return true or false
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equals(header))
			return true;

		return false;
	}

	/**
	 * 响应客户端json
	 * @author xue
	 * @date 2016-07-22
	 * @param o 响应内容
	 * @param response HttpServletResponse对象
	 */
	private void response(Object o, HttpServletResponse response) {
		try {
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragrma", "no-cache");
			response.setDateHeader("Expires", 0);

			response.setContentType("text/json; charset=utf-8");
			response.getWriter().write(o.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 创建SessionInfo对象
	 * @author xue
	 * @date 2016-08-13
	 * @param userModel 用户数据
	 * @param params 参数集
	 * @return SessionInfo
	 */
	public static SessionInfo createSessionInfo(UserModel userModel) {
		SessionInfo sessionInfo = new SessionInfo();
		// 用户登录成功后将登录信息放入session
		User user = new User();
		user.setUserId(userModel.getUserId());
		user.setUserCode(userModel.getUserCode());
		user.setMobile(userModel.getMobile());
		user.setUserName(userModel.getUserName());
		user.setOpenId(userModel.getOpenId());
		user.setWxName(userModel.getWxName());

		sessionInfo.setUser(user);
		
		return sessionInfo;
	}
}
